﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.SessionState;
using System.Net;
using BYFW.Encrypt;
using BYFW.BOL;

namespace BYFW.SFL
{
    public class CommonOP
    {
        /// <summary>
        /// 用于信息分割符
        /// </summary>
        public static string Spliter
        {
            get { return char.ConvertFromUtf32(300); }
        }
        /// <summary>
        /// 获得从DataRowCollection转换成的DataRow数组
        /// </summary>
        /// <param name="drc">DataRowCollection</param>
        /// <returns></returns>
        public static DataRow[] GetDataRowArray(DataRowCollection drc)
        {
            int count = drc.Count;
            DataRow[] drs = new DataRow[count];
            for (int i = 0; i < count; i++)
            {
                drs[i] = drc[i];
            }
            return drs;
        }
        /// <summary>
        /// 将DataRow数组转换成DataTable，注意行数组的每个元素须具有相同的数据结构，
        /// 否则当有元素长度大于第一个元素时，抛出异常
        /// </summary>
        /// <param name="rows">行数组</param>
        /// <returns></returns>
        public static DataTable GetTableFromRows(DataRow[] rows)
        {
            if (rows.Length <= 0)
            {
                return new DataTable();
            }
            DataTable dt = rows[0].Table.Clone();
            dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
            for (int i = 0; i < rows.Length; i++)
            {
                dt.LoadDataRow(rows[i].ItemArray, true);
            }
            return dt;
        }
        /// <summary>
        /// 数组中元素是否唯一
        /// </summary>
        /// <param name="arr">待判别数组</param>
        /// <returns></returns>
        public static bool IsUnique(Array arr)
        {
            int count = arr.Length;
            for (int i = 0; i < count - 1; i++)
            {
                for (int j = i + 1; j < count; j++)
                {
                    if (arr.GetValue(i).Equals(arr.GetValue(j)))
                    {
                        return false;
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 排序表的视图
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="sorts"></param>
        /// <returns></returns>
        public static DataTable SortedTable(DataTable dt, params string[] sorts)
        {
            if (dt.Rows.Count > 0)
            {
                string tmp = "";
                for (int i = 0; i < sorts.Length; i++)
                {
                    tmp += sorts[i] + ",";
                }
                dt.DefaultView.Sort = tmp.TrimEnd(',');
            }
            return dt;
        }
        /// <summary>
        /// 获取两位有效数字的金额
        /// </summary>
        /// <param name="currency"></param>
        /// <returns></returns>
        public static double GetCurrency(double currency)
        {
            return Math.Round(currency, 2);
        }
        /// <summary>
        /// 截断长字符串
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Ellipsis(string origin, int length)
        {
            string str = origin;
            if (origin.Length > length)
            {
                str = origin.Substring(0, length - 3) + "...";
            }
            return str;
        }
        /// <summary>
        /// 获取字符串指定范围字符的和
        /// </summary>
        /// <param name="origin">原始字符串</param>
        /// <param name="start">计算的开始位置</param>
        /// <param name="length">计算的字符串长度</param>
        /// <returns>字符串指定范围字符的和</returns>
        public static int GetStringSum(string origin, int start, int length)
        {
            int res = 0;
            for (int i = 0; i < length; i++)
            {
                if (start + i < origin.Length)
                {
                    res += char.ConvertToUtf32(origin, start + i);
                }
            }
            return res;
        }
        /// <summary>
        /// 获取字符求和后并映射到65-122之间的字符
        /// </summary>
        /// <param name="origin">原始字符串</param>
        /// <param name="start">计算的开始位置</param>
        /// <param name="length">计算的字符串长度</param>
        /// <returns>字符求和后映射到65-122之间的字符</returns>
        public static string GetMappedSum(string origin, int start, int length)
        {
            int res = GetStringSum(origin, start, length) % 58 + 65;
            return char.ConvertFromUtf32(res);
        }
        /// <summary>
        /// 反转字符串
        /// </summary>
        /// <param name="origin"></param>
        /// <returns></returns>
        public static string ReverseString(string origin)
        {
            char[] tmp = origin.ToCharArray();
            Array.Reverse(tmp);
            StringBuilder sb = new StringBuilder();
            sb.Append(tmp);
            return sb.ToString();
        }
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptString(string input)
        {
            return MD5.AddMD5Profix(Base64.Encrypt(MD5.AddMD5Profix(input)));
            //return Base64.Encrypt(MD5.AddMD5Profix(Base64.Encrypt(input)));
        }
        /// <summary>
        /// 解密加过密的字符串
        /// </summary>
        /// <param name="input"></param>
        /// <param name="throwException">解密失败是否抛异常</param>
        /// <returns></returns>
        public static string DecryptString(string input, bool throwException)
        {
            string res = "";
            try
            {
                res = input;// Base64.Decrypt(input);
                if (MD5.ValidateValue(res))
                {
                    return MD5.RemoveMD5Profix(Base64.Decrypt(MD5.RemoveMD5Profix(res)));
                }
                else
                {
                    throw new BaseCustomException("字符串无法转换成功！");
                }
            }
            catch
            {
                if (throwException)
                {
                    throw;
                }
                else
                {
                    return "";
                }

            }
        }

        /// <summary>
        /// 从指定的字符串中获取整数
        /// </summary>
        /// <param name="origin">原始的字符串</param>
        /// <param name="fullMatch">是否完全匹配，若为false，则返回字符串中的第一个整数数字</param>
        /// <returns>整数数字</returns>
        public static int GetInt(string origin, bool fullMatch)
        {
            if (string.IsNullOrEmpty(origin))
            {
                return 0;
            }
            origin = origin.Trim();
            if (!fullMatch)
            {
                string pat = @"-?\d+";
                Regex reg = new Regex(pat);
                origin = reg.Match(origin.Trim()).Value;
            }
            int res = 0;
            int.TryParse(origin, out res);
            return res;
        }
        /// <summary>
        /// 从指定的字符串中获取数字
        /// </summary>
        /// <param name="origin">原始的字符串</param>
        /// <param name="fullMatch">是否完全匹配，若为false，则返回字符串中的第一个数字</param>
        /// <returns>数字</returns>
        public static double GetDouble(string origin, bool fullMatch)
        {
            if (string.IsNullOrEmpty(origin))
            {
                return 0;
            }
            origin = origin.Trim();
            if (!fullMatch)
            {
                string pat = @"-?\d*\.?\d+";
                Regex reg = new Regex(pat);
                origin = reg.Match(origin.Trim()).Value;
            }
            double res = 0;
            double.TryParse(origin, out res);
            return res;
        }
        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <param name="session">保存验证码的Session</param>
        /// <returns>当有验证码是返回验证码字符串，否则返回null</returns>
        public static string GetImageValidateCode(HttpSessionState session)
        {
            if (session["ValidateImg"] is string)
            {
                return session["ValidateImg"].ToString();
            }
            return null;
        }
        /// <summary>
        /// 移除列表中的重复项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static List<T> RemoveRepeat<T>(List<T> list)
        {
            List<T> res = new List<T>();
            for (int i = 0; i < list.Count; i++)
            {
                if (!res.Contains(list[i]))
                {
                    res.Add(list[i]);
                }
            }
            return res;
        }
        /// <summary>
        /// 判断URL是否有效
        /// </summary>
        /// <param name="url">待判断的URL，可以是网页以及图片链接等</param>
        /// <returns>200为正确，其余为大致网页错误代码</returns>
        public static int GetUrlError(string url)
        {
            int num = 200;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                ServicePointManager.Expect100Continue = false;
                ((HttpWebResponse)request.GetResponse()).Close();
            }
            catch (WebException exception)
            {
                if (exception.Status != WebExceptionStatus.ProtocolError)
                {
                    return num;
                }
                if (exception.Message.IndexOf("500 ") > 0)
                {
                    return 500;
                }
                if (exception.Message.IndexOf("401 ") > 0)
                {
                    return 401;
                }
                if (exception.Message.IndexOf("404") > 0)
                {
                    num = 404;
                }
            }
            catch
            {
                num = 401;
            }
            return num;
        }
       
        /// <summary>
        /// 获取日期时间中的日期
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DateTime GetDate(DateTime dt)
        {
            return DateTime.Parse(dt.ToLongDateString());
        }

        private void Test()
        {
            List<int> l1 = new List<int>();
            l1.Add(1);
            l1.Add(1);
            l1.Add(2);
            l1.Add(1);
            List<int> l = RemoveRepeat<int>(l1);
            Console.WriteLine(l.Count == 2);

            List<string> l2 = new List<string>();
            l2.Add("1");
            l2.Add("1");
            l2.Add("2");
            l2.Add("1");
            List<string> l2_ = RemoveRepeat<string>(l2);
            Console.WriteLine(l2_.Count == 2);

            object o1 = new object();
            object o2 = new object();
            List<object> l3 = new List<object>();
            l3.Add(o1);
            l3.Add(o2);
            l3.Add(o1);
            l3.Add(o2);
            List<object> l3_ = RemoveRepeat<object>(l3);
            Console.WriteLine(l3_.Count ==2);
        }

        private void TestCompare()
        {
            string f1 = @"e:\f1.txt";
            string f2 = @"e:\f2.txt";
            string[] f1ls = System.IO.File.ReadAllText(f1).Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string[] f2ls = System.IO.File.ReadAllText(f2).Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<string> ls1 = new List<string>(f1ls);
            List<string> ls2 = new List<string>(f2ls);
            for (int i = 0; i < ls1.Count; i++)
            {
                if (ls2.Contains(ls1[i]))
                {
                    ls1.RemoveAt(i);
                    i--;
                }
            }
            for (int i = 0; i < ls1.Count; i++)
            {
                Console.WriteLine(ls1[i]);
            }
        }
    }
}
